package com.fbs.wowo.util.upload;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.fbs.wowo.exception.DataOverflowException;
import com.fbs.wowo.exception.ErrorCode;
import com.fbs.wowo.util.common.Constants;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Oss {

    //OSS配置
    private static final String OssEndpointPublic = Constants.getOssEndpointPublic();
    private static final String OssEndpointPrivate = Constants.getOssEndpointPrivate();
    private static final String OssAccessKeyId = Constants.getOssAccessKeyId();
    private static final String OssAccessKeySecret = Constants.getOssAccessKeySecret();
    private static final String OssBucketName = Constants.getOssBucketName();

    /**
     * 文件访问域名
     * @return
     */
    public static String getOssEndpointPublic() {
        return OssEndpointPublic;
    }

    /**
     * 文件访问域名
     * @return
     */
    public static String getOssEndpointPrivate() {
        return OssEndpointPrivate;
    }


    /**
     * 获取OSSkey
     * @return
     */
    public static String getOssAccessKeyId() {
        return OssAccessKeyId;
    }

    /**
     * 获取OSS密码
     * @return
     */
    public static String getOssAccessKeySecret() {
        return OssAccessKeySecret;
    }

    /**
     * 获取OSS存储空间名称
     * @return
     */
    public static String getOssBucketName() {
        return OssBucketName;
    }


    //上传
    public static String getFileUrl(MultipartFile file,String imgName,
                                    String endpoint,String accessKeyId,
                                    String accessKeySecret,String bucketName) {
        if(null == file){
            throw new DataOverflowException(ErrorCode.ERR_UPLOAD);
        }
        // 获取文件后缀名
        String suffix = getSuffix(file);
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            //判断文件容器是否存在，不存在则创建
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            String dateString =imgName+"/"+sdf.format(new Date()) + "." + suffix; // 20180322010634.jpg
            //上传文件
            ossClient.putObject(bucketName, dateString, new ByteArrayInputStream(file.getBytes()));
            //设置URL过期时间为100年，默认这里是int型，转换为long型即可
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 100);
            //设置读权限
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            //生成URL
            URL url = ossClient.generatePresignedUrl(bucketName, dateString, expiration);
            if (url != null) {
                return url.toString().replaceFirst(Oss.getOssEndpointPrivate(), Oss.getOssEndpointPublic());
            }
            throw new DataOverflowException(ErrorCode.ERR_UPLOAD);
        } catch (Exception e) {
            throw new DataOverflowException(ErrorCode.ERR_UPLOAD);
        }finally {
            // 关闭OSS服务
            ossClient.shutdown();
        }
    }

    // 获取文 MultipartFile 文件后缀名工具
    public static String getSuffix(MultipartFile fileupload) {
        String originalFilename = fileupload.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        return suffix;
    }


}
